package com.lxs.doc.rocess.demo;

import com.lxs.doc.rocess.util.ExcelConvertToHtmlUtil2;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.usermodel.*;
import org.dom4j.io.XMLResult;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTStyle;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;
import org.w3c.dom.Document;

import java.util.Arrays;
import java.util.List;

public class Demo3 {


    public static void main(String[] args) throws Exception {
        try {
            CTStyle style = CTStyle.Factory.newInstance();
            System.out.println("CTStyle 实例创建成功");
            // 尝试调用有问题的方珐
            if (style.isSetDefault()) {
                System.out.println("getDefault() 方法可用");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 1. 扩展支持的文件类型列表ists
        List<String> supportTypes = List.of(
                "pdf", "docx", "doc", "xlsx", "xls",  // 文档类
                "xmind", "xmind8",                     // XMind类
                "md", "jpg", "png", "jpeg"             // 原有支持类型
        );
//        String pathstring ="D:\\360MoveData\\Users\\14046\\Desktop\\神州数码_李杰_人员简历.xlsx";
        String pathoutExcel = "D:\\360MoveData\\Users\\14046\\Desktop\\DDDDDexcel.html";
//        String pathstring ="D:\\360MoveData\\Users\\14046\\Desktop\\作品-me.docx";
        String pathoutDoc = "D:\\360MoveData\\Users\\14046\\Desktop\\DDDDDocx.html";

        String pathstring ="D:\\360MoveData\\Users\\14046\\Desktop\\PDF_WORD.doc";
//        String pathoutDoc = "D:\\360MoveData\\Users\\14046\\Desktop\\DDDDDoc.html";

        String pathout1 = "D:\\360MoveData\\Users\\14046\\Desktop\\DDDDDpdf.html";

        File file = new File(pathstring);
        String[] substring = file.getName().split("\\.");
        String fileType = substring[1];
        if (!supportTypes.contains(fileType)) {
//            throw new Exception("不支持的文件格式，仅支持PDF/WORD/Excel/XMind/Markdown/图片");
        }
        // 2. 新增文件类型标记（区分预览方式）
        int isPreview = 0;
        String previewType = ""; // 标记预览类型：direct(直接预览)/html(转换为HTML)/image(XMind转图片)
        if (List.of("pdf", "jpg", "png", "jpeg").contains(fileType)) {
            isPreview = 1;
            previewType = "direct"; // 原生直接预览
        } else if (List.of("docx", "doc").contains(fileType)) {
            isPreview = 1;
            previewType = "html"; // 转换为HTML预览
            convertTOhtml(pathstring,pathoutDoc);
        } else if (Arrays.asList("xlsx", "xls").contains(fileType)) {
            // 2. Excel转HTML
            ExcelConvertToHtmlUtil2.convert(pathstring,pathoutExcel);
        }
        else if (List.of("xmind", "xmind8").contains(fileType)) {
            isPreview = 1;
            previewType = "image"; // 转换为图片预览
        }
    }


//    private static String convertWordToHtml(Long fileId, InputStream inputStream, String fileType) throws Exception {
//        String htmlContent = "";
//        if ("docx".equals(fileType)) {
//            XWPFDocument doc = new XWPFDocument(inputStream);
//            XHTMLOptions options = XHTMLOptions.create().indent(4);
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
//            XHTMLConverter.getInstance().convert(doc, out, options);
//            htmlContent = out.toString("UTF-8");
//        } else if ("doc".equals(fileType)) {
////            HWPFDocument doc = new HWPFDocument(inputStream);
////            HtmlDocumentConverter converter = new HtmlDocumentConverter(doc);
////            htmlContent = converter.getHtml();
//        }
//        // 存储HTML到MinIO
//        String convertedPath = String.format("%s/%s_convert.html", fileId, fileId);
////        minioClient.putObject(
////                PutObjectArgs.builder()
////                        .bucket(manualBucket)
////                        .object(convertedPath)
////                        .stream(new ByteArrayInputStream(htmlContent.getBytes()), htmlContent.getBytes().length, -1)
////                        .contentType("text/html")
////                        .build()
////        );
//        return convertedPath;
//    }

    /**
     * 有用
     * @param inputPath
     * @return
     * @throws IOException
     */
    public static void convertTOhtml(String inputPath,String outputPath) throws Exception {
        if(inputPath.endsWith("doc")){
           docToHtml(inputPath, outputPath);
        }
        if(inputPath.endsWith("docx")){
            docxToHtml(inputPath, outputPath);
        }
    }

    private static void docToHtml(String inputPath, String outputPath) {
        try (InputStream in = new FileInputStream(inputPath);
             HWPFDocument document = new HWPFDocument(in)) {

            // 创建转换器并处理文档
            WordToHtmlConverter converter = new WordToHtmlConverter(
                    javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()
            );
            converter.processDocument(document);

            // 获取转换后的DOM文档
            Document htmlDoc = (Document) converter.getDocument();
//            System.out.println("htmlDoc.getTextContent() = " + htmlDoc.getTextContent());
            // 输出到HTML文件
            try (FileOutputStream out = new FileOutputStream(outputPath)) {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.transform(new DOMSource(htmlDoc), new StreamResult(out));
                InputStream stream = new FileInputStream(outputPath);
                System.out.println("new String(stream.readAllBytes()) = " + new String(stream.readAllBytes()));

            } catch (TransformerConfigurationException e) {
                e.printStackTrace();
            } catch (TransformerException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }
    }

    private static void  docxToHtml(String inputPath, String outputPath) throws IOException {
        try (FileInputStream fis = new FileInputStream(inputPath);
             XWPFDocument document = new XWPFDocument(fis);
             FileOutputStream fos = new FileOutputStream(outputPath)) {

            StringBuilder html = new StringBuilder();
            html.append("<!DOCTYPE html><html><head><meta charset='UTF-8'></head><body>");

            // 处理段落
            for (XWPFParagraph p : document.getParagraphs()) {
                html.append("<p>");
                for (XWPFRun run : p.getRuns()) {
                    String text = run.getText(0);
                    if (text != null) {
                        // 保留基本样式
                        String style = "";
                        if (run.isBold()) style += "font-weight:bold;";
                        if (run.isItalic()) style += "font-style:italic;";
                        if (run.getColor() != null) style += "color:" + run.getColor() + ";";

                        html.append("<span style='").append(style).append("'>")
                                .append(text)
                                .append("</span>");
                    }
                }
                html.append("</p>");
            }

            // 处理表格
            for (XWPFTable table : document.getTables()) {
                html.append("<table border='1'>");
                for (XWPFTableRow row : table.getRows()) {
                    html.append("<tr>");
                    for (XWPFTableCell cell : row.getTableCells()) {
                        html.append("<td>");
                        // 递归处理单元格内的段落
                        for (XWPFParagraph para : cell.getParagraphs()) {
                            html.append(processParagraph(para));
                        }
                        html.append("</td>");
                    }
                    html.append("</tr>");
                }
                html.append("</table>");
            }

            // 处理图片（需手动实现图片提取和base64编码）
            for (XWPFParagraph p : document.getParagraphs()) {
                for (XWPFRun run : p.getRuns()) {
                    if (run.getEmbeddedPictures().size() > 0) {
                        for (XWPFPicture pic : run.getEmbeddedPictures()) {
                            byte[] data = pic.getPictureData().getData();
                            String base64 = java.util.Base64.getEncoder().encodeToString(data);
                            String ext = pic.getPictureData().getPackagePart().getPartName().getExtension();
                            html.append("<img src='data:image/")
                                    .append(ext)
                                    .append(";base64,")
                                    .append(base64)
                                    .append("'/>");
                        }
                    }
                }
            }

            html.append("</body></html>");
            fos.write(html.toString().getBytes());
//            System.out.println("html.toString() = " + html.toString());
//            return html.toString();
        }
    }

    private static String processParagraph(XWPFParagraph p){
        // 简化版段落处理逻辑
        return "<p>" + p.getText() + "</p>";
    }
}
